package com.ruoyi.web.controller.zzw;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.AccessTokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 *
 * @author linzhaojie
 */
@Api("小程序openid获取")
@RestController
@RequestMapping("/wechat")
public class WeChatController extends BaseController {

    @Value("${minProgram.appId}")
    private String appid;
    @Value("${minProgram.serret}")
    private String secret;
    @Autowired
    private RedisCache redisCache;

    @ApiOperation("小程序登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "code", dataType = "String", dataTypeClass = Integer.class)
    })
    @PostMapping(value = "/login", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public AjaxResult login(@RequestBody JSONObject codeJson) throws Exception {
        String code = codeJson.getString("code");
        JSONObject jsonObject;
        if (!isAlphaNumeric(code)) {
            return error("非法的code");
        } else {
            String jsonId = AccessTokenUtils.getOpenid(appid, secret, code);
            jsonObject = JSONObject.parseObject(jsonId);
        }

        return success(jsonObject);
    }
    public static boolean isAlphaNumeric(String str) {
        return str.matches("^[a-zA-Z0-9]+$");
    }

    @ApiOperation("小程序获取分享码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "跳转路径", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "scene", value = "邀请码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "check_path", value = "是否检查路径", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "env_version", value = "版本", dataType = "String", dataTypeClass = String.class)
    })
    @PostMapping(value = "/getShareCode", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public AjaxResult getShareCode(@RequestBody JSONObject paramObj) {
        JSONObject jsonObject = JSONObject.parseObject(redisCache.getCacheObject("token"));
        String token = jsonObject.getString("access_token");
        String codeStr = AccessTokenUtils.getShareCode(token,paramObj);
        JSONObject codeObj = JSONObject.parseObject(codeStr);
        return success(codeObj);
    }
}
